########################################################################
#  Searx-Qt - Lightweight desktop application for Searx.
#  Copyright (C) 2020-2022  CYBERDEViL
#
#  This file is part of Searx-Qt.
#
#  Searx-Qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-Qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################


import sys
import os
from datetime import datetime


class LogLevels:
    QUIET   = 0       # noqa: E221
    ERROR   = 1 << 1  # noqa: E221
    WARNING = 1 << 2  # noqa: E221
    INFO    = 1 << 3  # noqa: E221
    DEBUG   = 1 << 4  # noqa: E221


LogLevel = LogLevels.QUIET
# When enviroment variable 'SEARXQT_DEBUG' is set it will output all levels no
# matter what the LogLevel flags are.
DebugMode = True if os.getenv('SEARXQT_DEBUG', None) is not None else False
del os


def outputMessageFactory(name, level, out=sys.stdout):
    def decorator(func):
        def wrap(msg, cls=None):
            if not DebugMode and not (LogLevel & level):
                return
            if cls is None:
                cls = sys._getframe().f_back.f_code.co_name
            else:
                cls = cls.__module__
            print("{0} {1} <{2}>: {3}".format(
                    datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    name,
                    cls,
                    msg
                ),
                file=out,
                flush=DebugMode
            )
        return wrap
    return decorator


@outputMessageFactory('INFO', LogLevels.INFO, out=sys.stdout)
def info(msg, cls=None):
    pass


@outputMessageFactory('ERROR', LogLevels.ERROR, out=sys.stderr)
def error(msg, cls=None):
    pass


@outputMessageFactory('WARNING', LogLevels.WARNING, out=sys.stderr)
def warning(msg, cls=None):
    pass


@outputMessageFactory('DEBUG', LogLevels.DEBUG, out=sys.stderr)
def debug(msg, cls=None):
    pass
